package user

import (
	"errors"
	"gxcvu-ai/app/model"
	"gxcvu-ai/app/model/chat"
	"gxcvu-ai/pkg/database"
	"gxcvu-ai/pkg/hash"

	"gorm.io/gorm"
)

type User struct {
	model.BaseModal

	Name     string      `json:"name,omitempty" gorm:"size:100"`
	Email    string      `json:"email,omitempty" gorm:"size:50"`
	Password string      `json:"-"  gorm:"size:70"`
	Token    int64       `json:"token,omitempty"`
	Chat     []chat.Chat `json:"chats"`

	model.CommonTimestampsField
}

func (userModal *User) BeforeSave(tx *gorm.DB) (err error) {
	if !hash.IsHashed(userModal.Password) {
		userModal.Password = hash.PasswordHash(userModal.Password)
	}
	return
}

func UserLogin(username string, password string) (User, error) {
	var u User
	database.DB.
		Where("email = ?", username).
		First(&u)

	if u.ID == 0 {
		return User{}, errors.New("用户不存在")
	}

	if !hash.PasswordVerify(password, u.Password) {
		return User{}, errors.New("密码错误")
	}

	return u, nil
}

func (userModal *User) Create() {
	database.DB.Create(&userModal)
}
